package com.rx.sample.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.rx.sample.model.Balance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RefreshScope
@Slf4j
public class PaymentController {

    @Value("${sleep:0}")
    private int sleep;

    private final static Map<Integer, Balance> balanceMap = new HashMap() {{
        put(1, Balance.builder().id(1).diamond(10).ticket(1000).build());
        put(2, Balance.builder().id(2).diamond(0).ticket(10000).build());
        put(3, Balance.builder().id(3).diamond(100).ticket(0).build());
    }};

    @RequestMapping("/pay/balance")
    @SentinelResource(value = "protected-resource", blockHandler = "blockHandler")
    public Balance getBalance(Integer id) {
        log.info("request: /pay/balance?id={}, sleep: {}", id, sleep);
        if (sleep > 0) {
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (id != null && balanceMap.containsKey(id)) {
            return balanceMap.get(id);
        }
        return Balance.builder().build();
    }

    public Balance blockHandler(Integer id, BlockException e) {
        return Balance.builder().message("降级").build();
    }

}
